package com.qf.java2106.huangshengrui.hotel.controller;

import com.qf.java2106.huangshengrui.hotel.constant.MethodConstant;

import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author q
 * @version V1.0
 * @date 2021/10/26
 **/

public class BaseServlet extends HttpServlet {

    @Override
    public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {

        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        try {
            //获取method方法
            String methodName = request.getParameter(MethodConstant.METHOD);
            //反射调用方法
            Method method = this.getClass().getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
            String responseResult = (String) method.invoke(this,request, response);

            //无论是哪个方法作出的响应，无非就三种情况
            //请求转发   forward: 转发URL
            //重定向     redirect: 重定向的URL
            //直接响应字符串   字符串

            //统一处理响应结果
            //要跳转的目标资源
            String url = responseResult.substring(responseResult.indexOf(MethodConstant.TAG) + 1);

            if (responseResult.startsWith(MethodConstant.FORWARD_PREFIX)){
                request.getRequestDispatcher(url).forward(request,response);
            } else if (responseResult.startsWith(MethodConstant.REDIRECT_PREFIX)){
                response.sendRedirect(url);
            } else {
                response.getWriter().write(responseResult);
            }
        } catch (Exception e) {
            e.printStackTrace();
            response.getWriter().write("服务器正忙，请稍后重试！");
        }
    }
}
